<template>
  <div class="upload">
	<div class="gva-search-box">
	  <el-form ref="searchFormRef" :inline="true" :model="searchInfo">
	    <el-form-item label="统计月份" prop="statisticsMonth" :rules="[
    {
      required: true,
      message: '统计月份不能为空！',
      trigger: 'change',
    },
  ]">
			<el-date-picker type="monthrange" v-model="searchInfo.statisticsMonth" format="YYYY-MM" value-format="YYYY-MM"
			          :style="{width: '240px'}" start-placeholder="开始月份" end-placeholder="结束月份" range-separator="至"
			          clearable @change="selectMonth"></el-date-picker>
	    </el-form-item>
		<el-form-item label="小区">
			<el-input v-model="searchInfo.building" placeholder="请输入小区名称" clearable />
		</el-form-item>
	    <el-form-item label="显示列">
	      <el-select v-model="searchInfo.cols" clearable multiple placeholder="显示列" :style="{width: '510px'}">
	        <el-option v-for="(item, index) in showColumnOptions" :key="index" :label="item.value" :value="item.value" />
	      </el-select>
	    </el-form-item>
	    <el-form-item>
	      <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
	      <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
	    </el-form-item>
	  </el-form>
	</div>
	
    <div class="gva-table-box">
      <div class="gva-btn-list">
		<el-button class="excel-btn" size="small" type="primary" icon="download" @click="downloadFromxq()">抓取小区</el-button>
		<el-button class="excel-btn" size="small" type="primary" icon="download" @click="dialogFormVisible = true">抓取成交</el-button>
		<el-upload
          class="excel-btn"
          :action="`${path}/lj/import`"
          :headers="{'token':userStore.token}"
          :on-success="loadExcel"
          :show-file-list="false"
        >
          <el-button size="small" type="primary" icon="upload">导入自定义数据</el-button>
        </el-upload>
        <el-button class="excel-btn" size="small" type="success" icon="download" @click="downloadExcelTemplate()">下载模板</el-button>
        <el-button class="excel-btn" size="small" type="primary" icon="download" @click="handleExcelExport()">导出</el-button>
      </div>
      <el-table :data="tableData" row-key="ID" max-height="450">
		<el-table-column align="left" v-for="(item,index) in titleList" :label="item" show-overflow-tooltip min-width="100" :prop="item" :key="item" />
      </el-table>
	  <div class="gva-pagination">
		  <el-pagination
				v-model:currentPage="pageNumber"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100, 1000, 10000]"
				:total="total"
				background
				layout="total, sizes, prev, pager, next, jumper"
				@click="onSubmit"
				@current-change="onSubmit"
			  />
	  </div>
    </div>
	
	<el-dialog v-model="dialogFormVisible" title="抓取成交数据">
		<el-form ref="cjFormRef" :model="cjform">
		  <el-form-item label="火狐Cookie" :label-width="formLabelWidth" prop="cookie" :rules="[
    { 
		required: true, 
		message: 'Cookie不能为空！', 
		trigger: 'blur' ,
	},
  ]">
			<el-input v-model="cjform.cookie" type="textarea" :rows="10" autocomplete="off" placeholder="请复制火狐Cookie的JSON对象!" />
		  </el-form-item>
		  <el-form-item label="开始日期" :label-width="formLabelWidth" prop="startTime" :rules="[
    {
      type: 'date',
      required: true,
      message: '开始日期不能为空！',
      trigger: 'change',
    },
  ]">
			  <el-date-picker v-model="cjform.startTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="开始日期" />
		  </el-form-item>
		</el-form>
		<template #footer>
		  <span class="dialog-footer">
			<el-button @click="dialogFormVisible = false">取消</el-button>
			<el-button type="primary" @click="submitForm()">抓取</el-button>
		  </span>
		</template>
	</el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Village',
}
</script>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import { getLjXq, getLjCj, getLjImport, getLjList } from '@/api/vilage'
import { reactive, ref } from 'vue'
import qs from 'qs'

const path = ref(import.meta.env.VITE_BASE_PATH +":"+ import.meta.env.VITE_SERVER_PORT)

const showColumnOptions = ref([
	{
	  value: '统计均价',
	  label: '统计均价'
	},
  {
    value: '成交套数',
    label: '成交套数'
  },
  {
    value: '成交总价',
    label: '成交总价'
  },
  {
    value: '成交均价',
    label: '成交均价'
  },
  {
    value: '平均成交周期',
    label: '平均成交周期'
  }
])

const searchFormRef = ref({})
const searchInfo = ref({})
const titleList = ref([])
const tableData = ref([])
const pageNumber = ref(1)
const pageSize = ref(20)
const total = ref(0)

const cjFormRef = ref({})
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const cjform = ref({
  cookie: '',
  startTime: ''
})

const downloadFromxq = () => {
	ElMessageBox.confirm(
	    '是否立即抓取小区数据?',
	    '小区数据',
	    {
	      confirmButtonText: '立即抓取',
	      cancelButtonText: '取消',
	      type: 'warning',
	    }
	  )
	    .then(async() => {
	      const result = await getLjXq()
		  if (result.code === 0) {
			  ElMessage({
				type: 'success',
				message: '抓取小区数据完成！',
			  })
			}else{
				ElMessage({
					type: 'error',
					message: result.msg,
				})
			}
	    })
		.catch(() => {})
}

const submitForm = async() => {
	if (!cjFormRef) return
	await cjFormRef.value.validate((valid, fields) => {
		if (valid) {
			ElMessageBox.confirm(
				'是否立即抓取成交数据?',
				'成交数据',
				{
				  confirmButtonText: '立即抓取',
				  cancelButtonText: '取消',
				  type: 'warning',
				}
			  )
			.then(async() => {
				dialogFormVisible.value = false
			  const result = await getLjCj(cjform.value)
			  if (result.code === 0) {
					  ElMessage({
						type: 'success',
						message: '抓取成交数据完成！',
					  })
					}else{
						ElMessage({
							type: 'error',
							message: result.msg,
						})
					}
			})
			.catch(() => {})
		}
	})
}

const selectMonth = (v) => {
	if(v){
		const timeList = v.toString().split(",")
		searchInfo.value.timeStart = timeList[0]
		searchInfo.value.timeEnd = timeList[1]
	}else{
		searchInfo.value.timeStart = ""
		searchInfo.value.timeEnd = ""
	}
}

const onReset = () => {
  searchInfo.value = {}
}

// 搜索
const onSubmit = async() => {
	if (!searchFormRef) return
	await searchFormRef.value.validate((valid, fields) => {
		if (valid) {
		  getTableData()
		} else {
		  console.log('error submit!', fields)
		}
	})
}

// 查询
const getTableData = async() => {
	// 复制对象
	const param = {...searchInfo.value}
	// 删除不需要的参数
	delete param.statisticsMonth
  const result = await getLjList({ pageNumber: pageNumber.value, pageSize: pageSize.value, ...param })
  if (result.code === 0) {
	titleList.value = result.data.titleList
    tableData.value = result.data.dataList
    total.value = result.data.total
  }
}

const userStore = useUserStore()

const handleExcelExport = async() => {
	if (!searchFormRef) return
	await searchFormRef.value.validate((valid, fields) => {
		if (valid) {
			// 复制对象
		  	const param = {...searchInfo.value}
		  	// 删除不需要的参数
		  	delete param.statisticsMonth
		    window.location.href = path.value + '/lj/export?token=' + userStore.token + '&' + qs.stringify(param, {arrayFormat: 'repeat'})
		} else {
			console.log('error submit!', fields)
		}
	})
}
const loadExcel = () => {
	ElMessage({
		type: 'success',
		message: '导入自定义数据完成！',
	})
	onSubmit()
}
const downloadExcelTemplate = () => {
  window.location.href = path.value + '/excel/链家二手房自定义数据.xlsx'
}

</script>

<style lang="scss" scoped>
.btn-list{
  display: flex;
  margin-bottom: 12px;
  justify-content: flex-end;

}
.excel-btn+.excel-btn{
  margin-left: 10px;
}
</style>
